# -*- coding: utf-8 -*-

import logging
import traceback

from werkzeug.exceptions import HTTPException

from webutils_wechat.auth.flask import LoggedInUserResource
from utils.exceptions import FrontendException

from .. import namespaces as ns
from .. import marshals


logger = logging.getLogger(__name__)


@ns.user.route('/profile')
class UserProfile(LoggedInUserResource):
    @ns.user.marshal_with(marshals.user.user, envelope='data')
    def put(self):
        try:
            self.parser.add_argument('nickname')
            self.parser.add_argument('avatar')
            self.parser.add_argument('gender')
            self.parser.add_argument('city')
            self.parser.add_argument('province')
            self.parser.add_argument('country')
            self.parser.add_argument('language')
            self.parser.add_argument('encryptedData')
            self.parser.add_argument('iv')
            args = self.parser.parse_args()
            encrypted_data = args.pop('encryptedData', None)
            iv = args.pop('iv', None)

            if encrypted_data and iv:
                decrypted = self.app.wechat.decrypt_user_info(
                    self.user.session_key,
                    iv,
                    encrypted_data,
                )
                logger.info('Decrypted user info: %s', decrypted)
                if 'nickName' in decrypted and decrypted['nickName']:
                    args['nickname'] = decrypted['nickName']
                if 'gender' in decrypted and decrypted['gender']:
                    args['gender'] = decrypted['gender']
                if 'language' in decrypted and decrypted['language']:
                    args['language'] = decrypted['language']
                if 'city' in decrypted and decrypted['city']:
                    args['city'] = decrypted['city']
                if 'province' in decrypted and decrypted['province']:
                    args['province'] = decrypted['province']
                if 'country' in decrypted and decrypted['country']:
                    args['country'] = decrypted['country']
                if 'avatarUrl' in decrypted and decrypted['avatarUrl']:
                    args['avatar'] = decrypted['avatarUrl']
                if 'phoneNumber' in decrypted and decrypted['phoneNumber']:
                    args['mobile'] = decrypted['phoneNumber']

            self.user.update_profile(**args)
            self.app.redis.login_user(self.user)
        except HTTPException:
            raise
        except:
            logger.error(
                'Error while updating user profile. args: %s Err: %s',
                ns.user.payload,
                traceback.format_exc(),
            )
            raise FrontendException(
                errcode=200150,
            )
        return self.user
